import logging
import requests
from requests.auth import HTTPBasicAuth

from redash.destinations import *
from redash.utils import json_dumps, base_url
from redash.serializers import serialize_alert


class Webhook(BaseDestination):
    @classmethod
    def configuration_schema(cls):
        return {
            "type": "object",
            "properties": {
                "url": {"type": "string"},
                "username": {"type": "string"},
                "password": {"type": "string"},
            },
            "required": ["url"],
            "secret": ["password"],
        }

    @classmethod
    def icon(cls):
        return "fa-bolt"

    def notify(self, alert, query, dashboard, user, new_state, app, host, options):
        try:
            if dashboard is not None:
                url = "{host}/dashboards/{dashboard_id}".format(host=base_url(user.org), dashboard_id=dashboard.id)
            elif query is not None:
                url = "{host}/queries/{query_id}".format(host=base_url(user.org), query_id=query.id)
            else:
                url = "{host}/alerts/{alert_id}".format(host=base_url(user.org), alert_id=alert.id)

            if "oapi.dingtalk.com" in options.get("url"):
                data = {
                    "msgtype": "link",
                    "link": {
                        "articles" : [
                            {
                                "title" : alert.custom_subject,
                                "text" : alert.custom_body,
                                "messageUrl" : url,
                            }
                        ]
                    },
                    # "at": {
                    #     "atMobiles": [
                    #         "150XXXXXXXX"
                    #     ],
                    #     "atUserIds": [
                    #         "user123"
                    #     ],
                    #     "isAtAll": false
                    # }
                }
            elif "qyapi.weixin.qq.com" in options.get("url"):
                data = {
                    "msgtype": "news",
                    "news": {
                        "articles" : [
                            {
                                "title" : alert.custom_subject,
                                "description" : alert.custom_body,
                                "url" : url,
                            }
                        ],
                        # "mentioned_mobile_list":["13800001111","@all"]                        
                    }
                }
            else:
                data = {
                    "event": "alert_state_change",
                    "alert": serialize_alert(alert, full=False),
                    "url_base": host,
                }

                data["alert"]["description"] = alert.custom_body
                data["alert"]["title"] = alert.custom_subject

            headers = {"Content-Type": "application/json"}
            auth = (
                HTTPBasicAuth(options.get("username"), options.get("password"))
                if options.get("username")
                else None
            )
            resp = requests.post(
                options.get("url"),
                data=json_dumps(data),
                auth=auth,
                headers=headers,
                timeout=5.0,
            )
            if resp.status_code != 200:
                logging.error(
                    "webhook send ERROR. status_code => {status}".format(
                        status=resp.status_code
                    )
                )
        except Exception:
            logging.exception("webhook send ERROR.")


register(Webhook)
